package com.duolaibei.pay.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import com.duolaibei.pay.bean.PayOrder;
import com.duolaibei.pay.http.BaseCallback;
import com.duolaibei.pay.http.HttpRetrofit;
import com.duolaibei.pay.http.ParamsUtils;
import com.duolaibei.pay.http.Result;
import com.duolaibei.pay.http.api.ApiName;
import com.duolaibei.pay.http.api.SerivceApi;
import com.duolaibei.pay.utils.ProgressDialogUtils;
import com.duolaibei.pay.utils.ToastUtils;

import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by wangshuo on 2017/7/4.
 */

public class BrushCard2Activity extends BrushCardActivity {
    private static final String PAY_TYPE = "22";
    private PayOrder order = null;
    private String certificate_number;//凭证号
    private String reference_number;//参考号
    private String payState;//支付状态
    private String payreason;//失败原因

    @Override
    public void getOrderId() {
        //刷卡
        if (coollectMoney()) {
            String sum = value.getText().toString();//金额
            ProgressDialogUtils.showProgress(this, "正在下单...");
            HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class)
                    .getOrderId(
                            appidStr,
                            ApiName.GET_ORDER_ID, terminalNumber,
                    ParamsUtils.getOrderId(sum, PAY_TYPE),
                            sum,
                            PAY_TYPE)
                    .enqueue(new BaseCallback<Result<PayOrder>>() {
                @Override
                public void onResponse(Call<Result<PayOrder>> call, Response<Result<PayOrder>> response) {
                    ProgressDialogUtils.dismissProgress();
                    Log.v("-----", "------" + response.body());
                    if (response.code() == 200) {
                        if (response.body().getStatus().equals("1")) {
                            order = response.body().getData();
                            brushCard(order);
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showRequstOrderResult("下单失败");
                                }
                            });
                        }
                    }
                }

                @Override
                public void onFailure(Call<Result<PayOrder>> call, Throwable t) {
                    ProgressDialogUtils.dismissProgress();
                    showRequstOrderResult("下单失败");
                    Log.v("---onFailure--", "error message:" + t.getMessage());
                }
            });
        }
    }

    private void showRequstOrderResult(String message) {
        ToastUtils.showToast(BrushCard2Activity.this, message, 3000);
    }

    private void brushCard(PayOrder order) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk",
                "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
        intent.putExtra("transName", "0");
        intent.putExtra("appId", getPackageName());
        intent.putExtra("amount", getAmount(order.getTotal_amount()));
        intent.putExtra("barcodeType", "0");//0-银行卡
        intent.putExtra("orderNoSFT", order.getOut_trade_no());//订单号
        startActivityForResult(intent, 0);
    }

    //将交易金额统一处理成12位，不足12位的在前面补0
    private String getAmount(String amount) {
        int price = Integer.parseInt(amount.replace(".", ""));
        String temp = price + "";
        while (temp.length() < 12) {
            temp = "0" + temp;
        }
        return temp;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case Activity.RESULT_CANCELED:
                String reason = data.getStringExtra("reason");
                if (reason != null) {
                    ToastUtils.showToast(this, "交易取消", 3000);
                }
                break;
            case Activity.RESULT_OK:
                addOrder(data);
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void addOrder(final Intent data) {
        certificate_number = data.getStringExtra("traceNo");//用于交易撤销
        reference_number = data.getStringExtra("referenceNo");//用于退货
        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).addOrder(order.getRqcode_url(), order.getOut_trade_no(), certificate_number, order.getTotal_amount(), "shengpay.bankcard").enqueue(new BaseCallback<Result<Map<String, String>>>() {
            @Override
            public void onResponse(Call<Result<Map<String, String>>> call, Response<Result<Map<String, String>>> response) {
                ToastUtils.showToast(BrushCard2Activity.this, "订单成功传入后台");
                reset();
            }

            @Override
            public void onFailure(Call<Result<Map<String, String>>> call, Throwable t) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        addOrder(data);
                    }
                }, 10000);
                Log.v("onFailure", "error message :" + t.getMessage());
            }
        });
    }
}
